class ModalManager {
    constructor(app) {
        this.app = app;
        this.confirmModal = null;
        this.taskDetailModal = null;
        this.settingsModal = null;
        this.pendingDeleteTaskId = null;
        this.currentEditingTaskId = null;
    }

    init() {
        this.setupConfirmModal();
        this.setupTaskDetailModal();
        this.setupSettingsModal();
    }

    setupConfirmModal() {
        this.confirmModal = document.getElementById('deleteConfirmModal');
        const confirmCancel = document.getElementById('confirmCancel');
        const confirmDelete = document.getElementById('confirmDelete');

        // 取消按钮事件
        confirmCancel.addEventListener('click', () => {
            this.hideConfirmModal();
        });

        // 确认删除按钮事件
        confirmDelete.addEventListener('click', () => {
            if (this.pendingDeleteTaskId !== null) {
                this.app.deleteTask(this.pendingDeleteTaskId);
                this.hideConfirmModal();
            }
        });

        // 点击背景关闭弹窗
        this.confirmModal.addEventListener('click', (e) => {
            if (e.target === this.confirmModal) {
                this.hideConfirmModal();
            }
        });

        // ESC键关闭弹窗
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && this.confirmModal.classList.contains('show')) {
                this.hideConfirmModal();
            }
        });
    }

    async confirmDeleteTask(id) {
        // 获取任务信息用于确认弹窗
        console.log('[ModalManager] 准备删除任务，ID:', id);
        const task = this.app.taskManager.todos.find(t => t.id === id);
        if (!task) {
            console.warn('[ModalManager] 未找到要删除的任务，ID:', id);
            return;
        }

        // 设置弹窗内容
        console.log('[ModalManager] 找到待删除任务:', task);
        this.pendingDeleteTaskId = id;
        const confirmTaskNameElement = document.getElementById('confirmTaskName');
        if (!confirmTaskNameElement) {
            console.error('[ModalManager] 未找到确认弹窗的任务名称元素');
            return;
        }
        confirmTaskNameElement.textContent = task.text;

        // 显示弹窗
        console.log('[ModalManager] 显示确认删除弹窗');
        this.showConfirmModal();
    }

    showConfirmModal() {
        this.confirmModal.classList.add('show');
        // 聚焦到删除按钮
        setTimeout(() => {
            document.getElementById('confirmDelete').focus();
        }, 100);
    }

    hideConfirmModal() {
        this.confirmModal.classList.remove('show');
        this.pendingDeleteTaskId = null;
    }

    setupTaskDetailModal() {
        this.taskDetailModal = document.getElementById('taskDetailModal');
        this.deleteConfirmModal = document.getElementById('deleteConfirmModal');
        
        // 添加取消按钮事件
        const cancelBtn = document.getElementById('taskDetailCancel');
        if (cancelBtn) {
            cancelBtn.addEventListener('click', () => {
                this.hideTaskDetail();
            });
        }
        
        // 添加保存按钮事件
        const saveBtn = document.getElementById('taskDetailSave');
        if (saveBtn) {
            saveBtn.addEventListener('click', () => {
                this.saveTaskDetail();
            });
        }
        
        // 点击背景关闭弹窗
        this.taskDetailModal.addEventListener('click', (e) => {
            if (e.target === this.taskDetailModal) {
                this.hideTaskDetail();
            }
        });
        
        // ESC键关闭弹窗
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && this.taskDetailModal.classList.contains('show')) {
                this.hideTaskDetail();
            }
        });
    }

    showDeleteConfirm(taskId, taskText) {
        const taskNameElement = document.getElementById('confirmTaskName');
        if (taskNameElement) {
            taskNameElement.textContent = taskText;
        }
        
        this.currentDeleteTaskId = taskId;
        this.deleteConfirmModal?.classList.add('show'); // 修改这里
    }

    hideDeleteConfirm() {
        this.deleteConfirmModal?.classList.remove('show'); // 修改这里
        this.currentDeleteTaskId = null;
    }

    showTaskDetail(taskId) {
        const task = this.app.taskManager.getTaskById(taskId);
        if (!task) return;

        this.currentEditingTaskId = taskId;

        // 填充表单数据
        document.getElementById('taskDetailText').value = task.text;
        document.getElementById('taskDetailPomodoros').value = task.pomodoros;
        document.getElementById('taskDetailPriority').value = task.priority || 'medium';

        // 处理到期时间
        if (task.dueDate) {
            const dueDate = new Date(task.dueDate);
            document.getElementById('taskDetailDueDate').value = dueDate.toISOString().split('T')[0];
        } else {
            document.getElementById('taskDetailDueDate').value = '';
        }

        // 显示创建时间
        const createdAt = new Date(task.createdAt);
        document.getElementById('taskDetailCreatedAt').textContent = createdAt.toLocaleString('zh-CN');

        // 显示完成时间（如果已完成）
        const completedField = document.getElementById('taskDetailCompletedField');
        if (task.completed && task.completedAt) {
            const completedAt = new Date(task.completedAt);
            document.getElementById('taskDetailCompletedAt').textContent = completedAt.toLocaleString('zh-CN');
            completedField.style.display = 'block';
        } else {
            completedField.style.display = 'none';
        }

        // 显示弹窗
        this.taskDetailModal.classList.add('show');

        // 聚焦到文本输入框
        setTimeout(() => {
            document.getElementById('taskDetailText').focus();
        }, 100);
    }

    hideTaskDetail() {
        this.taskDetailModal.classList.remove('show');
        this.currentEditingTaskId = null;
        document.body.style.overflow = '';
    }

    async saveTaskDetail() {
        if (this.currentEditingTaskId === null) return;

        const text = document.getElementById('taskDetailText').value.trim();
        const pomodoros = parseInt(document.getElementById('taskDetailPomodoros').value);
        const priority = document.getElementById('taskDetailPriority').value;
        const dueDateValue = document.getElementById('taskDetailDueDate').value;

        // 验证输入
        if (!text) {
            alert('任务内容不能为空');
            return;
        }

        // 准备更新数据
        const updates = {
            text: text,
            pomodoros: pomodoros,
            priority: priority,
            dueDate: dueDateValue ? new Date(dueDateValue) : null
        };

        // 更新任务
        this.app.taskManager.updateTask(this.currentEditingTaskId, updates);
        await this.app.taskManager.saveTodos();

        // 更新UI
        this.app.uiRenderer.updateUI();

        // 关闭弹窗
        this.hideTaskDetail();
    }

    setupSettingsModal() {
        this.settingsModal = document.getElementById('settingsModal');
        const settingsBtn = document.getElementById('settingsBtn');
        const settingsClose = document.getElementById('settingsClose');

        // 检查设置按钮是否存在
        if (settingsBtn) {
            settingsBtn.addEventListener('click', () => {
                this.showSettingsModal();
            });
        }

        // 其他事件监听器也需要类似的检查
        if (settingsClose) {
            settingsClose.addEventListener('click', () => {
                this.hideSettingsModal();
            });
        }

        // 点击背景关闭弹窗
        this.settingsModal.addEventListener('click', (e) => {
            if (e.target === this.settingsModal) {
                this.hideSettingsModal();
            }
        });

        // ESC键关闭弹窗
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && this.settingsModal.classList.contains('show')) {
                this.hideSettingsModal();
            }
        });

        // 设置导航切换
        document.querySelectorAll('.settings-nav-item').forEach(item => {
            item.addEventListener('click', (e) => {
                const tab = e.currentTarget.dataset.tab;
                this.switchSettingsTab(tab);
            });
        });
    }

    showSettingsModal() {
        this.settingsModal.classList.add('show');
        document.body.style.overflow = 'hidden';
    }

    hideSettingsModal() {
        this.settingsModal.classList.remove('show');
        document.body.style.overflow = '';
    }

    switchSettingsTab(tab) {
        // 更新导航状态
        document.querySelectorAll('.settings-nav-item').forEach(item => {
            item.classList.remove('active');
        });
        document.querySelector(`[data-tab="${tab}"]`).classList.add('active');

        // 更新内容区域
        document.querySelectorAll('.settings-tab-content').forEach(content => {
            content.classList.remove('active');
        });
        document.getElementById(`${tab}-tab`).classList.add('active');
    }
}

module.exports = ModalManager;